import java.util.ArrayList;
import java.util.Observable;
import java.util.Random;

/*
 * ****************************
 * Eric Doherty
 * Jesse Kinney
 * 
 * TCSS 422 Scheduler simulator
 * General Process Class
 * 
 * 6/4/08
 * ****************************
 */

public class Process extends Observable
{
  private int pc;

  private final int NUMINSTRUCTIONS;

  private ArrayList<Integer> IOTimes;

  private static int nextPID = 0;

  private int ioDevice;

  private int pid;

  public Process()
  {
    pc = 0;
    NUMINSTRUCTIONS = 5000;
    pid = ++nextPID;

    ioDevice = new Random().nextInt(2);

    IOTimes = new ArrayList<Integer>();

    for (int i = 0; i < 3; i++)
    {
      IOTimes.add((int) (Math.random() * (NUMINSTRUCTIONS - 1) + 1));
    }
  }

  public int getPC()
  {
    return pc;
  }

  public void incrementPC()
  {
    pc = (pc + 1) % NUMINSTRUCTIONS;
  }

  public void doInstruction()
  {
    for (int i : IOTimes)
    {
      if (pc == i)
      {
        systemCall();
      }
    }
  }

  public void systemCall()
  {
    System.out.println("Process " + pid + " makes IO call");
    setChanged();

    if (ioDevice == 0)
      notifyObservers(new Event(Event.EventTypes.STARTIO1));
    else
      notifyObservers(new Event(Event.EventTypes.STARTIO2));
  }

  public String toString()
  {
    return this.getClass().getName();
  }

  public boolean equals(Object o)
  {
    boolean result = false;

    if (o instanceof Process)
    {
      Process p = (Process) o;
      if (p.pid == this.pid)
        result = true;
    }

    return result;
  }

  public int getPid()
  {
    return pid;
  }

}
